<template>
  <page-container>
    <app-card>
      <template #header>
        数据筛选
      </template>
      <el-form
        ref="form"
        :model="listParams"
        :disabled="listLoading"
        label-width="70px"
        inline
        @submit.prevent="initData"
      >
        <el-form-item label="文章分类">
          <el-select
            v-model="listParams.pid"
            placeholder="请选择"
            clearable
            @change="initData"
          >
            <el-option
              v-for="itemType in listType"
              :key="itemType.id"
              :label="itemType.title"
              :value="itemType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章搜索">
          <el-input
            v-model="listParams.title"
            placeholder="请输入"
            clearable
            style="width: 300px;"
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                @click="initData"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </app-card>
    <app-card>
      <template #header>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="$router.push('/admin/cms/article/add_article')"
        >
          添加文章
        </el-button>
      </template>
      <app-table
        :list="list"
        :list-loading="listLoading"
        :list-config="listConfig"
      />
      <app-pagination
        v-model:page="listParams.page"
        v-model:limit="listParams.limit"
        :list-count="listCount"
        :load-list="initData"
        :disabled="listLoading"
      />
    </app-card>
  </page-container>
  <rule-form
    v-model="formVisible"
    v-model:item="item"
    @success="handleFormSuccess"
  />
</template>

<script lang="tsx" setup>
import dayjs from 'dayjs'
import { Article, ArticleCategory, ArticleCategoryParams, ArticleParams } from '@/api/types/article'
import { onMounted, reactive, ref } from 'vue'
import * as api from '@/api/article'
import { ElMessage, ElMessageBox } from 'element-plus'
import RuleForm from './components/RuleForm.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const item = ref<Article | null>(null)
const formVisible = ref(false)
const list = ref<Article[]>([])
const listCount = ref(0)
const listType = ref<ArticleCategory[]>([])
const listLoading = ref(false)
const listConfig = reactive([
  { label: 'ID', prop: 'id', align: 'center', width: 80 },
  {
    label: '文章图片',
    prop: 'image_input',
    formatter: (row: Article) => {
      return (
        <el-image
          style="width: 50px; height: 50px"
          src={ row.image_input[0] || './src/assets/logo_small.png' }
          preview-src-list={ row.image_input }
          fit="fill"
        ></el-image>
      )
    }
  },
  { label: '文章名称', prop: 'title' },
  { label: '关联商品', prop: 'store_name' },
  { label: '浏览量', prop: 'visit' },
  {
    label: '时间',
    prop: 'add_time',
    sortable: true,
    formatter: (row: Article) => dayjs(Number(`${row.add_time}000`)).format('YYYY-MM-DD HH:mm')
  },
  {
    label: '操作',
    minWidth: '180px',
    fixed: 'right',
    align: 'center',
    formatter: (row: Article) => {
      return (
        <div>
          <el-button type="text" onClick={ () => { handleUpdate(row.id) } }>
            编辑
          </el-button>
          <el-button type="text" onClick={ () => { handleRelation(row) } }>
            { row.storeInfo ? '取消关联' : '关联' }
          </el-button>
          <el-popconfirm
            title="确认删除吗？"
            onConfirm={ () => { handleDelete(row.id) } }
            v-slots={{
              reference: () => (
                <el-button type="text">
                  删除
                </el-button>
              )
            }}
          >
          </el-popconfirm>
        </div>
      )
    }
  }
])
const listParams = ref<ArticleParams>({
  page: 1,
  limit: 10,
  pid: '',
  title: ''
})

onMounted(() => {
  initType()
  initData()
})

const initType = async () => {
  const params: ArticleCategoryParams = {
    type: 1
  }
  const data = await api
    .getArticleCategory(params)
  listType.value = data
}

const initData = async () => {
  listLoading.value = true
  const data = await api
    .getArticle(listParams.value)
    .finally(() => {
      listLoading.value = false
    })
  list.value = data.list
  listCount.value = data.count
}

const handleFormSuccess = () => {
  formVisible.value = false
  initData()
}

const handleRelation = async (row: Article) => {
  const { storeInfo, id } = row
  if (storeInfo) {
    return ElMessageBox.confirm(
      '确定要取消关联吗？',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        await api.putCmsUnRelation(id)
        ElMessage.success('取消关联成功')
        initData()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作'
        })
      })
  }
  formVisible.value = true
  item.value = row
}

const handleUpdate = (id: number) => {
  router.push({
    name: 'update_article',
    params: {
      id
    }
  })
}

const handleDelete = async (id: number) => {
  await api.deleteArticle(id)
  ElMessage.success('删除成功')
  initData()
}

</script>

<style lang="scss" scoped>

</style>
